<template>
	<div class="card-fill layout-padding" v-loading="loading" element-loading-text="Loading...">
		<el-card shadow="hover" class="layout-padding-auto create-form">
			<el-form ref="formRef" :model="stateData.vmModel" label-width="120px">
				<div class="form-section">
					<div class="section-title">
						<i class="_wtmicon _wtmicon-wxbzhanghu"></i>
						<span>基本信息</span>
					</div>

					<el-row :gutter="20">
						<el-col :xs="24" :lg="12" class="mb20">
							<el-form-item
								ref="Entity_TemplateName_FormItem"
								prop="Entity.TemplateName"
								:rules="[{ required: true, message: '模板名称为必填项', trigger: 'blur' }]"
							>
								<template #label>
									<WtmLabelTooltip label="模板名称" tooltip="模板的正式名称" />
								</template>
								<el-input v-model="stateData.vmModel.Entity.TemplateName" clearable class="width100"></el-input>
							</el-form-item>
						</el-col>
						<el-col :xs="24" :lg="12" class="mb20">
							<el-form-item ref="Entity_TemplateCode_FormItem" prop="Entity.TemplateCode">
								<template #label>
									<WtmLabelTooltip label="模板编码" tooltip="模板的唯一编码" />
								</template>
								<el-input v-model="stateData.vmModel.Entity.TemplateCode" clearable class="width100"></el-input>
							</el-form-item>
						</el-col>
						<el-col :xs="24" :lg="12" class="mb20">
							<el-form-item
								ref="Entity_TemplateType_FormItem"
								prop="Entity.TemplateType"
								:rules="[{ required: true, message: '模板类型为必填项', trigger: 'blur' }]"
							>
								<template #label>
									<WtmLabelTooltip label="模板类型" tooltip="模板的类型分类" />
								</template>
								<el-select v-model="stateData.vmModel.Entity.TemplateType" clearable class="width100" @change="onTemplateTypeChange">
									<el-option v-for="opt in templateTypeOptions" :key="opt.value" :value="opt.value" :label="opt.label" />
								</el-select>
							</el-form-item>
						</el-col>
						<el-col :xs="24" :lg="12" class="mb20">
							<el-form-item ref="Entity_SealId_FormItem" prop="Entity.SealId">
								<template #label>
									<WtmLabelTooltip label="印章选择" tooltip="选择要使用的印章（可选）" />
								</template>
								<el-select v-model="selectedSealId" clearable class="width100" placeholder="请选择印章" @change="onSealChange">
									<el-option label="不使用印章" value="" />
									<el-option v-for="seal in AllSysSeals" :key="seal.ID" :value="seal.ID" :label="seal.SealName">
										<div style="display: flex; align-items: center">
											<img v-if="seal.SealImage" :src="seal.SealImage" style="width: 20px; height: 20px; margin-right: 8px; object-fit: contain" />
											<span>{{ seal.SealName }}</span>
										</div>
									</el-option>
								</el-select>
							</el-form-item>
						</el-col>
					</el-row>
				</div>

				<div class="form-section">
					<div class="section-title">
						<i class="_wtmicon _wtmicon-wxbzhanghu"></i>
						<span>模板信息</span>
					</div>

					<el-row :gutter="20">
						<el-col :xs="24" :lg="24" class="mb20">
							<el-form-item
								ref="Entity_TemplateContent_FormItem"
								prop="Entity.TemplateContent"
								:rules="[{ required: true, message: '模板内容为必填项', trigger: 'blur' }]"
							>
								<template #label>
									<WtmLabelTooltip label="模板内容" tooltip="模板的主要内容，支持HTML格式" />
								</template>
								<!-- 使用新的HTML模版组件 -->
								<TemplateRenderer
									:template-type="stateData.vmModel.Entity.TemplateType"
									:template-content="stateData.vmModel.Entity.TemplateContent"
									:show-selector="false"
									:show-field-config="false"
									:show-actions="false"
									:preview-mode="true"
									:custom-styles="{ fontSize: '14px', lineHeight: '1.8' }"
									:enable-pdf="true"
									:pdf-file-name="`${stateData.vmModel.Entity.TemplateName || stateData.vmModel.Entity.TemplateType}.pdf`"
									:escape-field-values="true"
									:seal-data="sealDataForRenderer"
									ref="templateRendererRef"
								/>
							</el-form-item>
						</el-col>
					</el-row>
				</div>

				<div class="form-section">
					<div class="section-title">
						<i class="_wtmicon _wtmicon-wxbzhanghu"></i>
						<span>状态信息</span>
					</div>

					<el-row :gutter="20">
						<el-col :xs="24" :lg="12" class="mb20">
							<el-form-item
								ref="Entity_Status_FormItem"
								prop="Entity.Status"
								:rules="[{ required: true, message: '模板状态为必填项', trigger: 'blur' }]"
							>
								<template #label>
									<WtmLabelTooltip label="模板状态" tooltip="模板的当前状态" />
								</template>
								<el-select v-model="stateData.vmModel.Entity.Status" clearable class="width100">
									<el-option key="草稿" value="草稿" label="草稿"></el-option>
									<el-option key="正常" value="正常" label="正常"></el-option>
									<el-option key="停用" value="停用" label="停用"></el-option>
									<el-option key="归档" value="归档" label="归档"></el-option
								></el-select>
							</el-form-item>
						</el-col>
					</el-row>
				</div>

				<div class="form-section">
					<div class="section-title">
						<i class="_wtmicon _wtmicon-wxbzhanghu"></i>
						<span>版本信息</span>
					</div>

					<el-row :gutter="20">
						<el-col :xs="24" :lg="12" class="mb20">
							<el-form-item
								ref="Entity_Version_FormItem"
								prop="Entity.Version"
								:rules="[{ required: true, message: '模板版本为必填项', trigger: 'blur' }]"
							>
								<template #label>
									<WtmLabelTooltip label="模板版本" tooltip="模板的版本号" />
								</template>
								<el-input-number v-model="stateData.vmModel.Entity.Version" clearable class="width100"></el-input-number>
							</el-form-item>
						</el-col>
					</el-row>
				</div>

				<div class="form-section">
					<div class="section-title">
						<i class="_wtmicon _wtmicon-wxbzhanghu"></i>
						<span>其他信息</span>
					</div>

					<el-row :gutter="20">
						<el-col :xs="24" :lg="12" class="mb20">
							<el-form-item ref="Entity_Remarks_FormItem" prop="Entity.Remarks">
								<template #label>
									<WtmLabelTooltip label="备注信息" tooltip="模板的备注信息" />
								</template>
								<el-input v-model="stateData.vmModel.Entity.Remarks" clearable class="width100"></el-input>
							</el-form-item>
						</el-col>
					</el-row>
				</div>
			</el-form>
		</el-card>
	</div>
</template>

<script setup lang="ts" name="message._system.common.vm.add;false">
import { reactive, ref, onMounted, nextTick, getCurrentInstance, computed } from 'vue';
import { ElMessage } from 'element-plus';
import { useTemplate } from '/@/hooks/useTemplate';
import { templateConfigs } from '/@/hooks/useTemplate';
import TemplateRenderer from '/@/components/TemplateRenderer/index.vue';
import { SysTemplateApi } from '/@/views/common/systemplate/api';
import { SysSealApi } from '/@/views/common/sysseal/api';
import other from '/@/utils/other';

const BUTTON_TEXTS = {
	SAVE: '保存',
	SUBMIT: '提交',
	CLOSE: '关闭',
} as const;

// 定义接口
interface ISysTemplateVm {
	Entity: {
		ID?: number;
		TemplateName: string | null;
		TemplateCode: string | null;
		TemplateType: string;
		TemplateContent: string | null;
		SealId?: string | null;
		Status: string;
		Version: number;
		Remarks: string | null;
	};
	ActionName: string | null;
	IsMyApprove: boolean | null;
}

interface IViewModel<T> {
	vmModel: T;
}

// 获取API实例
const api = SysTemplateApi;
const sealApi = SysSealApi;

// 获取组件实例
const ci = getCurrentInstance();

// 表单引用
const formRef = ref();

// 模板渲染器引用
const templateRendererRef = ref();

// 加载状态
const loading = ref(false);

// 是否已保存过
const hasSavedOnce = ref(false);

// 印章列表
const AllSysSeals = ref<any[]>([]);

// 选中的印章ID
const selectedSealId = ref<string>('');

// 使用模板hook
const { selectTemplateType, setSealData, renderedContent } = useTemplate();
// 下拉项与给渲染器的印章数据
const templateTypeOptions = Object.keys(templateConfigs).map((k) => ({ value: k, label: k }));
const sealDataForRenderer = computed(() => {
	const seal = AllSysSeals.value.find((s) => s.ID === selectedSealId.value);
	return seal ? { id: seal.ID as string, name: seal.SealName as string, image: seal.SealImage as string } : null;
});

// 响应式数据
const stateData = reactive<IViewModel<ISysTemplateVm>>({
	vmModel: {
		Entity: {
			TemplateName: null,
			TemplateCode: null,
			TemplateType: '在职证明',
			TemplateContent: null,
			SealId: null,
			Status: '草稿',
			Version: 0,
			Remarks: null,
		},
		ActionName: null,
		IsMyApprove: null,
	},
});

// 模板类型选择监听
const onTemplateTypeChange = (templateType: string) => {
	if (templateType) {
		selectTemplateType(templateType);
		// 更新模板内容
		stateData.vmModel.Entity.TemplateContent = renderedContent.value;
	}
};

// 印章选择监听
const onSealChange = (sealId: string) => {
	if (sealId) {
		const selectedSeal = AllSysSeals.value.find((seal) => seal.ID === sealId);
		if (selectedSeal) {
			setSealData({
				id: selectedSeal.ID,
				name: selectedSeal.SealName,
				image: selectedSeal.SealImage,
			});
			stateData.vmModel.Entity.SealId = sealId;
		}
	} else {
		setSealData(null);
		stateData.vmModel.Entity.SealId = null;
	}

	// 更新模板内容以显示印章
	stateData.vmModel.Entity.TemplateContent = renderedContent.value;
};

const handleApiResponse = (response: any) => {
	ElMessage.success(ci?.proxy?.$t('message._system.common.vm.submittip') || '提交成功');
	emit('refresh');
	loading.value = false;
	closeDialog();
};

const handleError = (error: any) => {
	other.setFormError(ci, error);
	loading.value = false;
};

const handleApiRequest = (apiCall: () => Promise<any>, beforeSubmit: () => void, isSubmit = false) => {
	formRef.value?.validate((valid: boolean) => {
		if (valid) {
			loading.value = true;
			beforeSubmit();
			apiCall()
				.then((response: any) => handleApiResponse(response))
				.catch(handleError);
		}
	});
};

// 取消
const onClose = () => {
	closeDialog();
};

// 保存
const onSave = () => {
	handleApiRequest(
		() => {
			// 创建一个深拷贝，确保新增时不发送无效的 ID 字段
			const submitData = JSON.parse(JSON.stringify(stateData.vmModel));
			if (!submitData.Entity.ID) {
				// 如果没有有效的 ID，删除该字段
				delete submitData.Entity.ID;
			}
			return api().add(submitData);
		},
		() => {},
		false
	);
};

// 加载选择列表数据
const loadData = async () => {
	try {
		// 使用正确的 API 调用方式获取印章列表
		const sealsResponse = await sealApi().search({});
		if (sealsResponse.Data) {
			AllSysSeals.value = sealsResponse.Data.map((item: any) => ({
				ID: item.ID,
				SealName: item.SealName,
				SealImage: item.SealImage,
			}));
		}
	} catch (error) {
		console.warn('加载印章列表失败:', error);
		// 静默处理错误，不影响页面正常使用
	}
};

const initializePageData = () => {
	const wtmdata = ci?.attrs['wtmdata'] as any;
	if (wtmdata?.ID) {
		stateData.vmModel.Entity.ID = wtmdata.ID;
		hasSavedOnce.value = true;
	}
};

// 页面加载时
onMounted(async () => {
	loading.value = true;
	initializePageData();

	try {
		// 并行加载选择列表数据
		await loadData();

		// 初始化默认模板内容
		if (!stateData.vmModel.Entity.TemplateContent && stateData.vmModel.Entity.TemplateType) {
			onTemplateTypeChange(stateData.vmModel.Entity.TemplateType);
		}

		// 等待 DOM 更新完成
		await nextTick();
	} catch (error) {
		other.setFormError(ci, error);
	} finally {
		loading.value = false;
		nextTick(() => {
			setupHeaderButtons();
		});
	}
});

// 定义子组件向父组件传值事件
const emit = defineEmits(['refresh', 'closeDialog', 'updateHeaderButtons']);

// 关闭弹窗
const closeDialog = () => {
	emit('closeDialog');
};

const setupHeaderButtons = () => {
	const headerButtons = [
		{
			text: BUTTON_TEXTS.SUBMIT,
			type: 'primary',
			onClick: onSave,
			visible: true,
		},
		{
			text: BUTTON_TEXTS.CLOSE,
			type: 'default',
			onClick: onClose,
			visible: true,
		},
	];
	emit('updateHeaderButtons', headerButtons);
};
</script>

<style scoped>
/* 模版组件样式 */
.template-renderer {
	margin-top: 10px;
}
</style>
